<template>
  <d2-container class="page">
    <div style="position: relative;">
      <h4 class="my_header">体系架构列表</h4>
      <el-button type="warning" size="small" style="position: absolute;right: 205px;top: 0;" @click="downTXTemplate">模板导出</el-button>
<!--      <el-button type="success" size="mini" style="position: absolute;right: 70px;top: 0;" @click="addTXData(true)">体系架构导入</el-button>-->
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :multiple="false"
        :show-file-list="false"
        :on-preview="handlePreview"
        :on-success="fileSuccess"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :file-list="fileList"
        :accept="dictAccept"
      >
        <el-button style="position: absolute;right: 80px;top: 0;" size="small" type="primary">体系架构导入</el-button>
      </el-upload>
      <el-button type="primary" style="position: absolute;right: 0;top: 0;" size="small" @click="addTXData(true)">新增</el-button>
    </div>
    <div id="container">
      <div class="search bar6">
        <el-form ref="form" :model="search" label-width="80px">
          <el-input v-model="search.name" name="cname" placeholder="请输入名称、关键字等"></el-input>
          <button type="button" @click="getSysController"></button>
        </el-form>
      </div>
    </div>
    <div class="styleBox">
      <el-table
        :data="tableData"
        style="width: 100%"
        class="TXtable"
        border
        height="600"
        @row-click="showTree"
        highlight-current-row
        :row-class-name="tableRowClassName">
        <el-table-column label="序号" type="index" align="center" show-overflow-tooltip width="50px">
        </el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="名称">
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          align="center"
          prop="comment"
          label="背景">
        </el-table-column>
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          width="220">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="primary"-->
<!--              @click.stop="handleSee(scope.$index, scope.row, event)">三维演示-->
<!--            </el-button>-->
            <el-button
              type="warning"
              size="small"
              @click.stop="addTXData(false, scope.row)">修改</el-button>
            <el-button
              size="small"
              @click.stop="downloadTXFile(scope.row.id)">导出</el-button>
            <el-button
              type="danger"
              size="small"
              @click.stop="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!--新增-->
    <el-dialog :title="settingTitle" :visible.sync="settingVisible" width="30%">
          <el-row>
            <!-- ====================== -->
            <el-col class="stepBox">
              <el-form ref="form" :model="createData" label-width="80px" size="mini">
                <el-form-item label="名称：">
                  <el-input v-model="createData.name"></el-input>
                </el-form-item>
                <el-form-item label="背景：">
                  <el-input
                    type="textarea"
                    :rows="8"
                    placeholder="请输入内容"
                    v-model="createData.comment">
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button class="pull-right" type="primary" v-show="cOre" @click="createOrSaveSysStructure('create')">创建</el-button>
                  <el-button class="pull-right" type="primary" v-show="!cOre" @click="createOrSaveSysStructure('save')">更新</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
    </el-dialog>

    <v-contextmenu v-show="rightClickVisible" ref="itemContext">
      <div v-if="typeof(rightClickObj.level) != 'undefined' && rightClickObj.level == 1">
        <v-contextmenu-item @click="addScale">新增刻度信息</v-contextmenu-item>
      </div>
      <div v-if="typeof(rightClickObj.level) != 'undefined' && rightClickObj.level == 2">
        <v-contextmenu-item @click="addScaleChild">新增子刻度信息</v-contextmenu-item>
        <!--<v-contextmenu-item @click="handleClick()">新增仿真评估任务</v-contextmenu-item>-->
      </div>
      <v-contextmenu-item @click="delThreeNode">删除</v-contextmenu-item>
    </v-contextmenu>

    <!--  体系架构详情  -->
    <el-dialog :visible.sync="treeVisible" width="90%">
      <el-row>
        <!-- ====================== -->
        <el-col :span="7">
          <v-contextmenu ref="contextmenu">
            <v-contextmenu-item @click="addTXData">新增纬度信息</v-contextmenu-item>
          </v-contextmenu>
          <div class="TXTree" v-contextmenu:contextmenu>
            <h4 class="cardHeader">体系架构<div class="tree_node_op" style="float: right"><el-button style="margin: 3px 0px;" size="mini" @click="sortTreeData">排序保存</el-button></div></h4>
            <el-tree ref="tree" class="filter-tree" node-key="id" highlight-current default-expand-all
                     :expand-on-click-node="false" :data="TXTreeData" :props="defaultProps" @node-contextmenu="rightClick" @node-click="handleNodeClick" :render-content="renderContent"
                     draggable
                     @node-drop="handleDrop"
                     :allow-drop="allowDrop"
                     :allow-drag="allowDrag">
<!--              draggable-->
              <!--              @node-drag-start="handleDragStart"-->
<!--              @node-drag-enter="handleDragEnter"-->
<!--              @node-drag-leave="handleDragLeave"-->
<!--              @node-drag-over="handleDragOver"-->
<!--              @node-drag-end="handleDragEnd"-->
            </el-tree>
          </div>
        </el-col>

        <el-col :span="17">
          <v-contextmenu ref="contextmenu">
            <v-contextmenu-item @click="addDime">新增维度信息</v-contextmenu-item>
          </v-contextmenu>
          <div class="TXDetails">
            <h4 class="cardHeader">详情</h4>
<!--            <el-button class="btn" @click="drawer = true" size="mini" type="primary" >字典编辑</el-button>-->
            <el-form ref="form" class="dimensionInformation" v-show="informationType === 1" :model="dimeFormData" label-width="140px" size="mini">
              <el-form-item label="维度名称：">
                <el-input v-model="dimeFormData.name"></el-input>
              </el-form-item>
              <el-form-item label="含义：">
                <el-input type="textarea"
                          :rows="2" v-model="dimeFormData.mean"></el-input>
              </el-form-item>
<!--              <el-form-item label="指标：">-->
<!--                <el-input v-model="form.x"></el-input>-->
<!--              </el-form-item>-->
              <el-col :span="20">
                <el-form-item label="属性："
                              v-for="(domain) in dimeFormData.attributeTypes"
                              :key="domain.key">
                  <el-select v-model="domain.id"
                             filterable
                             allow-create
                             default-first-option
                             placeholder="请选择" @change="attrTypeChange">
                    <el-option
                      v-for="item in attrTypeAllData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <el-button style="margin-left: 20px;" type="danger" v-show="!(domain.type===1)" @click.prevent="removeDomain(domain,1)">删除</el-button>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="属性：" v-if="showText">
                  <el-input v-model="attrType" style="display: inline-block;max-width: 300px;margin-right: 20px;"/>
                  <el-button @click="createDictType" type="success" plain>创建</el-button>
                </el-form-item>
              </el-col>
<!--              <el-col :span="14">-->
<!--                <el-form-item label="指标："-->
<!--                                               v-for="(domain) in dimeFormData.attributes"-->
<!--                                               :key="domain.key">-->
<!--                <el-autocomplete-->
<!--                  class="inline-input"-->
<!--                  v-model="domain.val"-->
<!--                  :fetch-suggestions="querySearch"-->
<!--                  placeholder="请输入内容"-->
<!--                  clearable-->
<!--                  @select="handleSelect"-->
<!--                >-->
<!--                </el-autocomplete>-->
<!--&lt;!&ndash;                  <span style="width: 20px;display: inline-block;"> </span>&ndash;&gt;-->
<!--&lt;!&ndash;                  <el-button type="default" v-show="showSaveBtn" @click="saveAttrData(domain)">保存</el-button>&ndash;&gt;-->
<!--                  <span style="width: 20px;display: inline-block;"> </span>-->
<!--                  <el-button type="danger" v-show="!(domain.type===1)" @click.prevent="removeDomain(domain,1)">删除</el-button>-->
<!--              </el-form-item>-->
<!--              </el-col>-->
              <el-col>
                <el-form-item>
                  <el-button @click="addDomain(1)" type="info" plain>添加属性</el-button>
                  <el-button @click="addDomain(1, true)" type="primary" plain>创建属性</el-button>
                  <el-button class="btnSave pull-right" type="primary" v-show="cOre" @click="informationSave(1)">保存</el-button>
                </el-form-item>
              </el-col>
            </el-form>
            <el-form ref="form" class="scaleInformation" v-show="informationType === 2" :model="scaleFormData" label-width="140px" size="mini">
              <el-form-item label="刻度名称：">
                <el-input v-model="scaleFormData.name"></el-input>
              </el-form-item>
              <el-form-item label="含义：">
                <el-input type="textarea"
                          :rows="2" v-model="scaleFormData.mean"></el-input>
              </el-form-item>
              <el-col :span="10">
                <el-form-item label="属性："
                              v-for="(domain) in scaleFormData.attributeTypes"
                              :key="domain.key">
                  <el-select v-model="domain.id"
                             v-bind:disabled="domain.type==2"
                             placeholder="请选择" @change="attrTypeChange">
                    <el-option
                      v-for="item in attrTypeAllData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="指标："
                              v-for="(domain) in scaleFormData.attributeTypes"
                              :key="domain.key">
<!--                  <el-select v-model="domain.attribute.val" filterable placeholder="请选择">-->
<!--                    <el-option-->
<!--                      v-for="item in restaurants"-->
<!--                      :key="item.id"-->
<!--                      :label="item.val"-->
<!--                      :value="item.id">-->
<!--                    </el-option>-->
<!--                  </el-select>-->
                  <el-autocomplete
                    class="inline-input"
                    v-model="domain.attribute.val"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入内容"
                    clearable
                    @focus="getAll(domain.id)"
                    @select="handleValSelect"
                  >
                  </el-autocomplete>
                  <span style="width: 20px;display: inline-block;"> </span>
                  <el-button type="danger" v-show="!(domain.type===1)" @click.prevent="removeDomain(domain,2)">删除</el-button>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="属性：" v-if="showText">
                  <el-input v-model="attrType" style="display: inline-block;max-width: 300px;margin-right: 20px;"/>
                </el-form-item>
                <el-form-item label="指标：" v-if="showText">
                  <el-input type="textarea"
                            :rows="2"
                            placeholder="请输入指标" v-model="attrData" style="display: inline-block;max-width: 300px;margin-right: 20px;"/>
                  <el-button @click="createDictData" type="success" plain>创建</el-button>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item>
                  <el-button @click="addDomain(2)" type="info" plain>添加属性</el-button>
                  <el-button @click="addDomain(2, true)" type="primary" plain>创建属性</el-button>
                  <el-button class="btnSave pull-right" type="primary" v-show="cOre" @click="informationSave(2)">保存</el-button>
                </el-form-item>
              </el-col>
            </el-form>
            <el-form ref="form" class="scaleChildInformation" v-show="informationType === 3" :model="scaleChildFormData" label-width="140px" size="mini">
              <el-form-item label="子刻度名称：">
                <el-input v-model="scaleChildFormData.name"></el-input>
              </el-form-item>
              <el-form-item label="含义：">
                <el-input type="textarea"
                          :rows="2" v-model="scaleChildFormData.mean"></el-input>
              </el-form-item>
              <el-col :span="10">
                <el-form-item label="属性："
                              v-for="(domain) in scaleChildFormData.attributeTypes"
                              :key="domain.key">
                  <el-select v-model="domain.id"
                             v-bind:disabled="domain.type==1"
                             placeholder="请选择" @change="attrTypeChange">
                    <el-option
                      v-for="item in attrTypeAllData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="指标："
                              v-for="(domain) in scaleChildFormData.attributeTypes"
                              :key="domain.key">
                  <el-autocomplete
                    class="inline-input"
                    v-model="domain.attribute.val"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入内容"
                    v-bind:disabled="domain.type==1"
                    clearable
                    @focus="getAll(domain.id)"
                    @select="handleSelect"
                  >
                  </el-autocomplete>
                  <span style="width: 20px;display: inline-block;"> </span>
                  <el-button type="danger" v-show="!(domain.type===1)" @click.prevent="removeDomain(domain,3)">删除</el-button>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="属性：" v-if="showText">
                  <el-input v-model="attrType" style="display: inline-block;max-width: 300px;margin-right: 20px;"/>
                </el-form-item>
                <el-form-item label="指标：" v-if="showText">
                  <el-input type="textarea"
                            :rows="2"
                            placeholder="请输入指标" v-model="attrData" style="display: inline-block;max-width: 300px;margin-right: 20px;"/>
                  <el-button @click="createDictData" type="success" plain>创建</el-button>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item>
                  <el-button @click="addDomain(3)" type="info" plain>添加属性</el-button>
                  <el-button @click="addDomain(3, true)" type="primary" plain>创建属性</el-button>
                  <el-button class="btnSave pull-right" type="primary" v-show="cOre" @click="informationSave(3)">保存</el-button>
                </el-form-item>
              </el-col>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <el-drawer
      size="70%"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose">
      <DictPage></DictPage>
    </el-drawer>
  </d2-container>
</template>

<script>
import { delSysFramework, getList, getTXTree, saveSysFramework, saveTXTree } from '@api/sys.controller'
import { delDime, dimeSave, getDime } from '@api/dimension.controller'
import { delScale, getSacle, scaleSave } from '@api/scale.controller'
import { getAttrAll, getAttrList, saveAttr } from '@api/attr'
import { getAttrTypeAll, saveAttrType } from '@api/attr.type'
import DictPage from '../dict'

export default {
  name: 'legendSetting',
  components: {
    DictPage
  },
  data () {
    return {
      showText: false,
      attrType: null,
      attrData: null,
      drawer: false,
      direction: 'btt',
      uploadUrl: process.env.VUE_APP_API + 'import/system_excel_data',
      dictAccept: '.xls,.xlsx',
      TXID: 0,
      attrTypeAllData: [],
      currentAttrTypeId: '',
      cOre: true,
      showSaveBtn: false,
      search: {},
      informationType: 1,
      TXTreeData: [],
      restaurants: [],
      // TXTreeData: [
      //   {
      //     name: 'x轴',
      //     level: 1,
      //     children: [
      //       { name: '刻度一',
      //         level: 2,
      //         children: [
      //           { name: '子刻度一', level: 3 },
      //           { name: '子刻度二', level: 3 }
      //         ]
      //       },
      //       { name: '刻度二', level: 2 },
      //       { name: '刻度三', level: 2 }
      //     ]
      //   },
      //   { name: 'x轴', level: 1 },
      //   { name: 'x轴', level: 1 }
      // ],
      defaultProps: {
        label: `name`
        // children: `trees`,
        // parentId: `pid`
      },
      settingVisible: false,
      treeVisible: false,
      rightClickVisible: false,
      treeTitle: '体系架构信息',
      settingTitle: null,
      fileList: [],
      isCreateOrEdit: 'create',
      rightClickObj: {},
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      dictData: [],
      dddd: [],
      currentAttrs: [],
      active: 0,
      createData: { name: '', comment: '', id: '', createTime: '' },
      dimeFormData: {
        attribute: {},
        attributes: []
      },
      scaleFormData: {
        attribute: {},
        attributes: []
      },
      scaleChildFormData: {
        attribute: {},
        attributes: []
      },
      currentNode: {},
      form: {
        domains: [{}]
      },
      form1: {},
      form2: {
        xVal: 10,
        yVal: 3,
        zVal: 3
      },
      xVal: 10,
      yVal: 3,
      zVal: 3,
      form3: {},
      margin: 1.5
    }
  },
  watch: {
    currentAttrTypeId () {
      let DictQuery = {
        't': {
          'attributeTypeId': this.currentAttrTypeId
        }
      }
      getAttrList(DictQuery).then(res => {
        let newData = []
        res.list.filter((item, index) => {
          // item.value = item.val + '(' + item.attributeTypeName + ')'
          item.value = item.val
          newData[index] = item
        })
        this.restaurants = newData
      })
    }
  },
  created () {
    getAttrTypeAll().then(data => {
      this.attrTypeAllData = data
    })
    this.$EventBus.$on('updateDictList', () => {
      // 获取属性
      getAttrTypeAll().then(data => {
        this.attrTypeAllData = data
      })
      // 获取所有指标
      getAttrAll().then(res => {
        let newData = []
        res.filter((item, index) => {
          // item.value = item.val + '(' + item.attributeTypeName + ')'
          item.value = item.val
          newData[index] = item
        })
        this.restaurants = newData
        // console.log(this.restaurants)
      })
    })
  },
  methods: {
    renderContent (h, { node, data, store }) {
      let className = ''
      let styleTxt = ''
      if (node.level === 1) {
        className = 'el-icon-folder-opened'
        styleTxt = 'color:brown;'
      } else if (node.level === 2) {
        className = 'el-icon-folder'
        styleTxt = 'color:darkorange;'
      } else {
        className = 'el-icon-document'
        styleTxt = 'color:tomato;'
      }
      return (<span class='custom-tree-node'><i class={className} style={styleTxt}></i><span style="margin-left: 5px;">{node.label}</span></span>)
    },
    onClose () {
      this.$emit('close')
    },
    loadAll () {
      // return [
      //   { 'value': '三全鲜食（北新泾店）', 'id': '11112121', 'type': 0, 'address': '长宁区新渔路144号' },
      //   { 'value': 'Hot honey 首尔炸鸡（仙霞路）', 'address': '上海市长宁区淞虹路661号' }
      // ]

    },
    handleClose (done) {
      done()
    },
    querySearch (queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      if (results.length === 0) {
        this.showSaveBtn = true
      }
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter (queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect (item) {
      // 去除组件重复值
      if (item.val) {
        this.scaleChildFormData.attributeTypes.forEach((k) => {
          if (k.attribute.val === item.val) {
            // console.log(11)
            k.attribute = item
          }
        })
        this.currentAttrs = this.scaleChildFormData.attributeTypes
      } else {
        let newData = []
        this.currentAttrs.forEach((i) => {
          if (i.name) {
            newData.push(i)
          }
        })
        // 将新数据赋值给currentAttrs
        this.currentAttrs = newData
        this.currentAttrs.push(item)
      }
      // 添加原有数据
      // console.log(this.currentAttrs)
    },
    getAll (id) {
      let DictQuery = {
        't': {
          'attributeTypeId': id
        }
      }
      getAttrList(DictQuery).then(res => {
        let newData = []
        res.list.filter((item, index) => {
          // item.value = item.val + '(' + item.attributeTypeName + ')'
          item.value = item.val
          newData[index] = item
        })
        this.restaurants = newData
        // console.log(this.restaurants)
      })
    },
    handleValSelect (key) {
      // this.currentAttrs.forEach(item => {
      //   // console.log(item.attribute, key)
      //   if (item.attribute.val === key.val) {
      //     // console.log(11)
      //     item.attribute = key
      //   }
      // })
      if (typeof this.scaleFormData.id !== 'undefined') {
      // scaleFormData
        this.scaleFormData.attributeTypes.forEach((item) => {
          if (item.attribute.val === key.val) {
            // console.log(11)
            item.attribute = key
          }
        })
        this.currentAttrs = this.scaleFormData.attributeTypes
      }
    },
    addDomain (val, isCreate) {
      isCreate = isCreate || false
      if (isCreate) {
        // 是新创建的话显示创建框
        this.showText = true
      } else {
        // 否则在选择框中选择
        if (val === 1) {
          //  维度
          this.dimeFormData.attributeTypes.push({
            attribute: {},
            value: '',
            key: Date.now()
          })
        } else if (val === 2) {
          //  刻度
          this.scaleFormData.attributeTypes.push({
            attribute: {},
            value: '',
            key: Date.now()
          })
        } else if (val === 3) {
          //  子刻度
          this.scaleChildFormData.attributeTypes.push({
            attribute: {},
            value: '',
            key: Date.now()
          })
        }
      }
    },
    removeDomain (item, val) {
      if (val === 1) {
        // 维度属性删除
        let index = this.dimeFormData.attributeTypes.indexOf(item)
        if (index !== -1) {
          this.dddd.splice(index, 1)
          this.currentAttrs = this.dddd
          // this.dimeFormData.attributeTypes.splice(index, 1)
          // this.scaleFormData.attributes.splice(index, 1)
        }
      } else if (val === 2) {
        // 刻度属性指标删除
        let index = this.scaleFormData.attributeTypes.indexOf(item)
        if (index !== -1) {
          this.currentAttrs.splice(index, 1)
          this.ddd = this.currentAttrs
          // this.scaleFormData.attributeTypes.splice(index, 1)
          // this.scaleFormData.attributes.splice(index, 1)
        }
      } else if (val === 3) {
        // 子刻度属性指标删除
        let index = this.scaleChildFormData.attributeTypes.indexOf(item)
        if (index !== -1) {
          this.currentAttrs.splice(index, 1)
          this.ddd = this.currentAttrs
          // this.scaleChildFormData.attributeTypes.splice(index, 1)
          // this.scaleFormData.attributes.splice(index, 1)
        }
      }
    },
    showTree (row, column, event) {
      // 显示体系架构树状结构
      this.dimeFormData = {
        attribute: {},
        attributeTypes: []
      }
      this.scaleFormData = {
        attribute: {},
        attributes: []
      }
      this.scaleChildFormData = {
        attribute: {},
        attributes: []
      }

      this.TXID = row.id
      getTXTree(row.id).then(res => {
        this.TXTreeData = res
      }).catch(() => {
        this.$message.error('获取体系架构数据异常')
      })
      this.treeVisible = true
    },
    rightClick (event, object, value, element) {
      /**
       * @Function rightClick 任务树右击
       *
       */
      // console.log(object)
      this.isCreateOrEdit = 'create'
      this.showText = false
      this.currentNode = object
      this.getTXData(object) // 右击选中节点渲染数据
      this.rightClickVisible = true
      this.rightClickObj = object
      document.addEventListener('click', (e) => {
        this.rightClickVisible = false
      })
      // 右键的位置
      // console.log(this.$refs['itemContext'])
      let menu = this.$refs['itemContext'].$el
      menu.style.left = event.clientX + 20 + 'px'
      menu.style.top = event.clientY - 20 + 'px'
      menu.style.position = 'absolute'
    },
    downloadTXFile (id) {
      window.location.href = process.env.VUE_APP_API + 'down/system_excel_data?sysId=' + id
    },
    downTXTemplate () {
      window.location.href = process.env.VUE_APP_API + 'down/system_excel_template'
    },
    handleEdit () {
    },
    handleDelete (index, row) {
      //  删除体系架构信息
      let id = row.id
      this.$confirm('确认删除？', '删除体系', {
        distinguishCancelAndClose: true,
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          delSysFramework(id).then(() => {
            this.getSysController()
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          })
        })
        .catch(action => {
          this.$message({
            type: 'info',
            message: action === 'cancel'
              ? '放弃删除'
              : '取消删除'
          })
        })
    },
    getTXData (obj) {
      // 获取体系数据
    },
    getSysController () {
      let query = {
        'num': this.currentPage,
        'size': this.pageSize,
        't': {
          'name': this.search.name
        }
      }
      getList(query).then(res => {
        this.total = res.count
        this.tableData = res.list
      })
    },
    tableRowClassName ({ row, rowIndex }) {
      if (rowIndex % 3 === 1) {
        return 'warning-row'
      } else if (rowIndex % 3 === 3) {
        return 'success-row'
      }
      return ''
    },
    addTXData (val, row) {
      /* 新增体系架构数据 */
      row = row || null
      /* 新增体系架构数据 */
      if (val === true) {
        this.createData = { name: '', comment: '', id: '', createTime: '' }
        this.cOre = true
        this.settingTitle = '新增体系架构'
      } else {
        this.createData = row
        this.cOre = false
        this.settingTitle = '修改体系架构'
      }
      this.settingVisible = true
    },
    createOrSaveSysStructure (val) {
      //  创建体系架构信息
      saveSysFramework(this.createData).then(() => {
        this.settingVisible = false
        this.getSysController()
        if (val === 'create') {
          this.$message.success('创建成功')
        } else {
          this.$message.success('更新成功')
        }
      })
    },
    editSysStructure () {
      //  修改体系架构信息
    },
    handleNodeClick (data) {
      this.isCreateOrEdit = 'edit'
      this.showText = false
      this.currentAttrs = []
      // 树节点被点击的时候
      this.currentNode = data
      let level = data.level
      if (level === 1) {
        //  维度信息
        this.informationType = 1
        getDime(data.id).then(res => {
          this.dddd = res.attributeTypes
          this.currentAttrs = res.attributeTypes
          this.dimeFormData = res
        })
      } else if (level === 2) {
        // 刻度信息
        this.informationType = 2
        this.dddd = []
        getSacle(data.id).then(res => {
          this.dddd = res.attributeTypes
          this.currentAttrs = res.attributeTypes
          this.scaleFormData = res
        })
      } else if (level === 3) {
        // 子刻度信息
        this.informationType = 3
        getSacle(data.id).then(res => {
          this.dddd = res.attributeTypes
          this.currentAttrs = res.attributeTypes
          this.scaleChildFormData = res
        })
      }
    },
    addDime () {
    //  新增维度信息
      this.dddd = []
      this.currentAttrs = []
      this.informationType = 1
      this.dimeFormData = {
        attribute: {},
        attributeTypes: []
      }
    },
    addScale () {
      this.dddd = []
      this.currentAttrs = []
      //  新增刻度信息
      this.informationType = 2
      this.scaleFormData = {
        attribute: {},
        attributes: []
      }
    },
    addScaleChild () {
      //  新子刻度信息
      this.dddd = []
      this.currentAttrs = []
      this.informationType = 3
      this.scaleChildFormData = {
        attribute: {},
        attributes: []
      }
    },
    remoType () {
      let newData = []
      this.currentAttrs.forEach((item) => {
        if (item.type !== 1) {
          newData.push(item)
        }
      })
      this.currentAttrs = newData
    },
    informationSave (val) {
      if (val === 1) {
        //  维度信息提交
        let id = this.dimeFormData.id || ''
        let data = {
          'id': id,
          'sysId': this.TXID,
          'name': this.dimeFormData.name,
          'mean': this.dimeFormData.mean,
          'attributeTypes': this.currentAttrs
        }
        dimeSave(data).then((newData) => {
          // 更新树结构
          getDime(newData.id).then(res => {
            this.dddd = res.attributeTypes
            this.currentAttrs = res.attributeTypes
            this.dimeFormData = res
          })
          getTXTree(this.TXID).then(res => {
            this.TXTreeData = res
          })
          this.$message.success('保存成功')
        })
      } else if (val === 2) {
        // 刻度信息提交
        let parentID = null
        if (this.isCreateOrEdit === 'edit') {
          parentID = this.currentNode.parent_id
        } else {
          parentID = this.currentNode.id
        }
        let id = this.scaleFormData.id || ''
        let data = {
          'id': id,
          'parentId': parentID,
          'target': this.scaleFormData.target,
          'name': this.scaleFormData.name,
          'mean': this.scaleFormData.mean,
          'attributeTypes': this.currentAttrs
          // 'attributes': this.scaleFormData.attributes
        }
        scaleSave(data).then((newData) => {
          // console.log(newData)
          // 重新更新树信息
          getTXTree(this.TXID).then(res => {
            this.TXTreeData = res
          })
          // 重新获取刻度信息
          getSacle(newData.id).then(res => {
            this.dddd = res.attributeTypes
            this.currentAttrs = res.attributeTypes
            this.scaleFormData = res
          })
          this.$message.success('保存成功')
        })
      } else if (val === 3) {
        // 子刻度信息提交
        // 去除type为1 的attr
        let parentID = null
        if (this.isCreateOrEdit === 'edit') {
          parentID = this.currentNode.parent_id
        } else {
          parentID = this.currentNode.id
        }
        this.remoType()
        let id = this.scaleChildFormData.id || ''
        let data = {
          'id': id,
          'parentId': parentID,
          'target': this.scaleChildFormData.target,
          'name': this.scaleChildFormData.name,
          'mean': this.scaleChildFormData.mean,
          'attributeTypes': this.currentAttrs
        }
        scaleSave(data).then((newData) => {
          // 重新获取子刻度信息
          getSacle(newData.id).then(res => {
            this.dddd = res.attributeTypes
            this.currentAttrs = res.attributeTypes
            this.scaleChildFormData = res
          })
          getTXTree(this.TXID).then(res => {
            this.TXTreeData = res
          })
          this.$message.success('保存成功')
        })
      }
    },
    delThreeNode () {
      let level = this.currentNode.level
      if (level === 1) {
        delDime(this.currentNode.id).then(() => {
          getTXTree(this.TXID).then(res => {
            this.TXTreeData = res
          })
          this.$message.success('删除成功！')
        }).catch(() => {
          this.$message.error('删除操作异常！')
        })
      } else {
        delScale(this.currentNode.id).then(() => {
          getTXTree(this.TXID).then(res => {
            this.TXTreeData = res
          })
          this.$message.success('删除成功！')
        }).catch(() => {
          this.$message.error('删除操作异常！')
        })
      }
    },
    prev () {
      if (this.active-- < 0) this.active = 2
    },
    next () {
      if (++this.active > 2) this.active = 0
    },
    onsubmit () {
      // 生成图例
      window.location.href = '/'
    },
    handleSee (index, row) {
      window.location.href = '/'
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    fileSuccess (response, file, fileList){
      if (response.code === 0) {
        this.getSysController()
        this.$message.success('字典数据上传成功！')
      } else {
        this.$message.error('文件格式错误，请重新上传！')
      }
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getSysController()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getSysController()
    },
    attrTypeChange (val) {
      //  当前添加的字典类型改变时 设置当前选中的类型
      let i = null
      this.attrTypeAllData.forEach((item) => {
        if (item.id === val) {
          i = item
        }
      })
      this.handleSelect(i)
      this.currentAttrTypeId = val
      // this.currentAttrs = []
    },
    createDictType () {
      // 创建属性
      let obj = {
        id: '',
        name: this.attrType,
        comment: ''
      }
      saveAttrType(obj).then((success) => {
        // 创建成功之后刷新界面
        this.$EventBus.$emit('updateDictList')
        this.attrType = null
        this.showText = false
        this.currentAttrs.push(success)
      })
    },
    createDictData () {
      // 创建属性
      let obj = {
        id: '',
        name: this.attrType,
        comment: ''
      }
      saveAttrType(obj).then((success) => {
        // console.log(success)
        // 创建成功之后刷新界面
        let data = {
          id: '',
          val: this.attrData,
          comment: '',
          attributeTypeId: success.id
        }
        // console.log(data)
        saveAttr(data).then((obj) => {
          // console.log(obj)
          this.showText = false
          success.attribute = obj
          this.attrType = null
          this.attrData = null
          this.$EventBus.$emit('updateDictList')
          this.currentAttrs.push(success)
        })
        // this.showText = false
        // this.currentAttrs.push(success)
      })
    },
    saveAttrData (current) {
    //  点击保存的时候将指标保存于指定字典类型中
      let data = {
        comment: '',
        id: '',
        code: '',
        attributeTypeId: this.currentAttrTypeId,
        val: current.val
      }
      saveAttr(data).then((data) => {
        current = data.data
      })
    },
    save () {

    },
    handleDragStart (node, ev) {
      console.log('拖动开始', node)
    },
    handleDragEnter (draggingNode, dropNode, ev) {
      console.log('拖进: ', dropNode.label)
    },
    handleDragLeave (draggingNode, dropNode, ev) {
      console.log('拖着离开: ', dropNode.label)
    },
    handleDragOver (draggingNode, dropNode, ev) {
      console.log('拖过: ', dropNode.label)
    },
    handleDragEnd (draggingNode, dropNode, dropType, ev) {
      console.log('拖动结束: ', dropNode && dropNode.label, dropType)
    },
    handleDrop (draggingNode, dropNode, dropType, ev) {
      this.getNodeTree(this.TXTreeData)
      // console.log(this.TXTreeData)
      // console.log(draggingNode)
      console.log('拖动落下: ', dropNode.label, dropType)
    },
    allowDrop (draggingNode, dropNode, type) {
      if (draggingNode.data.parent_id === dropNode.data.parent_id) {
        return type !== 'inner'
      }
    },
    allowDrag (draggingNode) {
      // 判断节点能否被拖拽
      // return draggingNode.data.label.indexOf('三级 3-2-2') === -1
      if (draggingNode.data.id) {
        return true
      } else {
        return false
      }
    },
    getNodeTree (tree) {
      for (let i in tree) {
        tree[i].serNum = Number(i) + 1
        // console.log(tree[i])
        if (tree[i].children.length > 0) {
          this.getNodeTree(tree[i].children)
        // } else {
        //   console.log(i)
        }
      }
    },
    sortTreeData () {
      // 排序后提交新数据
      // console.log(this.TXTreeData)
      saveTXTree(this.TXTreeData).then(() => {
        this.$message.success('排序保存成功！')
      })
    }
  },
  mounted () {
    this.getSysController()
    getAttrAll().then(res => {
      let newData = []
      res.filter((item, index) => {
        // item.value = item.val + '(' + item.attributeTypeName + ')'
        item.value = item.val
        newData[index] = item
      })
      this.restaurants = newData
    })
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.stepBox {
  min-height: 250px;
}

.my_header {
  font-size: 22px;
  height: 40px;
  line-height: 40px;
  margin: 0px;
  border-bottom: 1px solid #ff5500;
}

.page .el-table tr.warning-row {
  /*background: oldlace !important;*/
}

.d2-container-full__body {
  background-color: transparent !important;
}

.page .el-table tr.success-row {
  background: #f0f9eb;
}

.el-pagination {
  text-align: center;
  background: floralwhite;
}

.TXTree, .TXDetails {
  font-size: 16px;
  height: 620px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  margin-right: 10px;
}

.cardHeader {
  padding-left: 5px;
  font-size: 22px;
  text-transform: uppercase;
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  letter-spacing: 2px;
  color: #ed2553;
  font-weight: 700;
  position: relative;
}

.cardHeader .btn{
  float: right;
  /*margin-right: 20px;*/
}

.cardHeader::before {
  content: "";
  width: 5px;
  height: 100%;
  position: absolute;
  top: 0;
  left: -10px;
  background: #ed2553;
}

#container {
  width:100%;
  height:80px;
  margin:0 auto;
}
div.search {
  padding:10px 0;
}
div.search form {
  position:relative;
  width:600px;
  margin:0 auto;
}
div.search input,div.search button {
  border:none;
  outline:none;
}
div.search button {
  height:40px;
  width:100px;
  cursor:pointer;
  position:absolute;
}

/*搜索框6*/

.bar6 input {
  border: 2px solid #ed2553 !important;
  border-radius: 5px;
  background: transparent;
  top: 0;
  right: 0;
}

.bar6 button {
  background: #ed2553;
  border-radius: 0 5px 5px 0;
  width: 80px;
  top: 0;
  right: 0;
}

.bar6 button:before {
  content: "搜索";
  font-size: 18px;
  color: #F9F0DA;
}
</style>
